/*
 * @Author: 杨上漂
 * @Date: 2024-10-12 17:34:53
 * @LastEditors: 杨上漂
 * @LastEditTime: 2024-10-16 17:15:59
 * @FilePath: \gwlc\assets\scripts\Enemy.ts
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
 */
import { _decorator, Color, Component, director, dragonBones, find, macro, Node, Pool, resources, Skeleton, sp, Sprite, TERRAIN_HEIGHT_BASE, Tween, tween, UITransform, v2, v3 } from 'cc';
import { EnemyMgr } from './EnemyMgr';
import { Player } from './Player';
import { gameMgr } from './gameMgr';

import { enemyStatusEnum, enemyTypeEnum, playerSkillTypeEnum } from '../Enum';
import { UserInfo } from '../startScene/UserInfo';
import { PoolMgr } from '../PoolMgr';
import { getDistance, isNearlyEqual, randomNum, trackTarget } from '../utils/utils';
import { StartSceneGameMgr } from '../startScene/StartSceneGameMgr';
import { AudioMgr } from '../utils/AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends Component {
    
    firingTempUpdateTime = 0;
    frozenTempUpdateTime = 0;
    scorchTempUpdateTime = 0;

    currfiringAlreadlyTime=0;//当前已经灼烧的时间

    currFrozenAlreadlyTime=0;//当前已经冰冻的时间

    currScorchAlreadlyTime=0;//当前已经烧焦的时间

    enemyId;

    maxHp = 2;

    currHp = this.maxHp;

    speed=30;

    attackMun=1;

    isDie=false;

    isAttacking=false;

    tempPlayerWorldPos=v3();

    enemyRoot:Node

    isNotMove=false;

    private isSufferTornadoIng = false;//是否正在遭受到龙卷风

    get IsSufferTornadoIng() {
        return this.isSufferTornadoIng;
    }
    set IsSufferTornadoIng(value) {
        if (value==this.isSufferTornadoIng) {
            return;
        }

        this.isSufferTornadoIng = value;
        if (value==true) {
            this.schedule(this.tornadoDamageFuc,0.3,macro.REPEAT_FOREVER,0.5);
            this.isNotMove=true;

            // if (this.node.x>0) {
                
            // }
        }
        else{
            console.log("取消龙卷风")
            // if(this._tornadoSchedule){
                this.unschedule(this.tornadoDamageFuc);
            // }
            this.isNotMove=false;
            this.node.angle=0;
        }
    }

    tornadoDamageFuc(){
        if (getDistance(this.node.position.x,this.node.position.y,0,0)<120) {
            this.CurrHp-=120;
            gameMgr.ins.creatMinTip(this.node.position,"120",false)
        }
       
    }

    enemyTp;

    set CurrHp(value: number) {
        if (value <= 0) {

            this.die();
            return;
        }
     
        if (this.CurrHp > value) {
            //扣血效果
            if (this.EnemyStatus!=enemyStatusEnum.frozen&&this.EnemyStatus!=enemyStatusEnum.scorch) {
                // Tween.stopAllByTag(12);
                this.node.getChildByName("sp").getComponent(sp.Skeleton).color = Color.RED
                tween(this.node)
                    .tag(12)
                    .by(0.1, { position: v3(0, 5, 0) })
                    .call(() => {
                        this.node.getChildByName("sp").getComponent(sp.Skeleton).color = Color.WHITE
                    })
                    .start()
            }
         

        }
        this.currHp = value;
    }

    get CurrHp() {
        return this.currHp
    }

    enemyStatus = 0;

    set EnemyStatus(value) {
        if (value!=enemyStatusEnum.none) {
            if (this.enemyStatus == value||this.enemyStatus!=enemyStatusEnum.none) {//不要重复输入状态,已经有状态了不要输入状态
                return;
            }
        }
       
        this.enemyStatus = value;
        this.node.getChildByName("lightingStatusDragon").active = false;
        this.node.getChildByName("fireSparkStatusDragon").active = false;
        this.node.getChildByName("sp").getComponent(sp.Skeleton).color = Color.WHITE;


        if (value == enemyStatusEnum.firing) {
            //更新敌人状态特效
            // gameMgr.ins.createSkeleton("skillDragon/FireSpark",this.node.getChildByName("statusDragon").getComponent(dragonBones.ArmatureDisplay))
            this.node.getChildByName("fireSparkStatusDragon").active = true;
        }
        else if(value == enemyStatusEnum.frozen){
            this.node.getChildByName("sp").getComponent(sp.Skeleton).color = new Color().fromHEX("#753FFF");
        }
        else if(value == enemyStatusEnum.scorch){
            this.node.getChildByName("sp").getComponent(sp.Skeleton).color = new Color().fromHEX("#181818");
           

        }
    }

    get EnemyStatus() {
        return this.enemyStatus;
    }

    tempPosition = v3();

    protected onLoad(): void {
        this.enemyRoot=find("Canvas/bg/enemyRoot");
    }

    init(_enemyId,_enemyTypeEnum) {
        this.enemyId = _enemyId;
        this.enemyTp=UserInfo.enemyCongfiDic.get(_enemyTypeEnum);

        //赋值

        if (StartSceneGameMgr.ins.sceneGateLevel <= 1) {
            this.maxHp = parseInt(this.enemyTp.maxHp);

        } else {
           
            this.maxHp = parseInt(this.enemyTp.maxHp) + ((StartSceneGameMgr.ins.sceneGateLevel - 1) * 16);
        }

        this.currHp = this.maxHp;
        this.speed = this.enemyTp.speed;
        this.attackMun=this.enemyTp.attack;

        resources.loadDir(this.enemyTp.spinesPath,sp.SkeletonData,(err,data)=>{
            if(err){
                console.log(err);
                return;
            }else{
                let comp = this.node.getChildByName("sp").getComponent(sp.Skeleton);
                comp.skeletonData = data[0];
                comp.setAnimation(0,"run",true);
            }
        })

        console.log(_enemyTypeEnum,"敌人类型")
        if (_enemyTypeEnum == enemyTypeEnum.putongjiangshi) {
            let randCount = randomNum(1, 100);
            if (randCount < 40) {
                AudioMgr.ins.playOneShot("audio/putongjiangshijiao", 0.6);
            }
        }

        if (_enemyTypeEnum == enemyTypeEnum.huopaojianghsi) {
            let randCount = randomNum(1, 100);
            if (randCount < 40) {
                AudioMgr.ins.playOneShot("audio/huopaojianghsijiao", 0.6);
            }
        }

        if (_enemyTypeEnum == enemyTypeEnum.lunyijiangshi) {
            let randCount = randomNum(1, 100);
            if (randCount < 40) {
                AudioMgr.ins.playOneShot("audio/lunyijiangshijiao", 0.6);
            }
        }

        if (_enemyTypeEnum == enemyTypeEnum.juxingjiangshi) {
            let randCount = randomNum(1, 100);
            if (randCount < 40) {
                AudioMgr.ins.playOneShot("audio/juxingjiangshijiao", 0.6);
            }
        }

        this.reSet();

    }

    reSet(){//重新设置数据，针对池拿来
        this.unscheduleAllCallbacks();

        this.firingTempUpdateTime = 0;
        this.frozenTempUpdateTime = 0;
        this.scorchTempUpdateTime = 0;
    
        this.currfiringAlreadlyTime=0;//当前已经灼烧的时间
    
        this.currFrozenAlreadlyTime=0;//当前已经冰冻的时间
    
        this.currScorchAlreadlyTime=0;//当前已经烧焦的时间
    
        this.isDie=false;
    
        this.isAttacking=false;

        this.IsSufferTornadoIng=false;

        this.EnemyStatus=enemyStatusEnum.none;

        this.node.getChildByName("dieDragon").active=false;
        this.node.getChildByName("lightingStatusDragon").active = false;
        this.node.getChildByName("fireSparkStatusDragon").active = false;
    }

     zzz=0;
    protected update(dt: number): void {
        
        if (!gameMgr.ins.isGamePause) {
            if (this.enemyStatus!=enemyStatusEnum.frozen) {
                if (this.isNotMove==false&&this.isAttacking==false) {
                    this.node.getPosition(this.tempPosition);
                    this.tempPosition.y -= dt * this.speed;
                    this.node.setPosition(this.tempPosition);
                }
            }

            Player.ins.node.getWorldPosition(this.tempPlayerWorldPos);
            

            if (this.EnemyStatus==enemyStatusEnum.firing) {
                this.firingTempUpdateTime += dt;
                if (this.firingTempUpdateTime > 1) {
                    this.firingTempUpdateTime = 0;
                    this.currfiringAlreadlyTime+=1

                    if (this.currfiringAlreadlyTime >= Player.ins.FiringSustainTime) {//灼烧持续时间结束
                        this.currfiringAlreadlyTime = 0
                        this.EnemyStatus = enemyStatusEnum.none;
                    }
                    else {//灼烧
                        this.CurrHp -= Player.ins.FiringDamage;//每秒减去灼烧伤害
                        gameMgr.ins.creatMinTip(this.node.position, `${Player.ins.FiringDamage}`,false);
                    }
                }

            }

            if (this.EnemyStatus==enemyStatusEnum.frozen) {
                this.frozenTempUpdateTime += dt;
                if (this.frozenTempUpdateTime > 1) {
                    this.frozenTempUpdateTime = 0;
                    this.currFrozenAlreadlyTime+=1

                    if (this.currFrozenAlreadlyTime >= Player.ins.moonFrozenSustainTime) {//持续时间结束
                        this.currFrozenAlreadlyTime = 0
                        this.EnemyStatus = enemyStatusEnum.none;
                    }
                }
            }

            if (this.EnemyStatus==enemyStatusEnum.scorch) {
                this.scorchTempUpdateTime+= dt;
                if (this.scorchTempUpdateTime > 1) {
                    this.scorchTempUpdateTime = 0;
                    this.currScorchAlreadlyTime+=1

                    if (this.currScorchAlreadlyTime >= Player.ins.lightScorchSustainTime) {//持续时间结束
                        console.log("持续时间结束")
                        this.currScorchAlreadlyTime = 0
                        this.EnemyStatus = enemyStatusEnum.none;
                    }
                }
            }

            if (this.isSufferTornadoIng) {
                this.tornadoTrackTargetMove(v3(0,0,0),this.node,200,dt)
            }
    
        }

        this.zzz+=dt;
        if (this.zzz>0.7) {
            this.zzz=0;
            var attakDistance = this.enemyRoot.getComponent(UITransform).convertToNodeSpaceAR(this.tempPlayerWorldPos).y + 210

            if (this.node.position.y < attakDistance) {//敌人越界攻击玩家
                if (this.isAttacking == false) {
                    this.isAttacking = true
                    if (gameMgr.ins.attackEnemyList.indexOf(this.enemyId) == -1) {
                        gameMgr.ins.attackEnemyList.push(this.enemyId)
                    }
                    if (gameMgr.ins.IsPlayerDieTimeDowning == false) {
                        if (gameMgr.ins.failPanel.active == false) {
                            gameMgr.ins.IsPlayerDieTimeDowning = true;
                        }
                    }
                }
            } else {
                if (this.isAttacking) {
                console.log("僵尸上移动")

                    this.isAttacking=false;
                    if (gameMgr.ins.attackEnemyList.indexOf(this.enemyId) != -1) {
                        for (let i = gameMgr.ins.attackEnemyList.length - 1; i >= 0; i--) {
                            if (gameMgr.ins.attackEnemyList[i] == this.enemyId) {
                                console.log('移除僵尸id', gameMgr.ins.attackEnemyList[i])
                                gameMgr.ins.attackEnemyList.splice(i, 1);
                            }
                        }
                    }
                    console.log(gameMgr.ins.attackEnemyList,"gameMgr.ins.attackEnemyList查看")
                }

            }

        }
    }

    tornadoTempPos=v3();
    /**
  * @description: 面向敌人移动
  * @return {*}
  */
    tornadoTrackTargetMove(targetPos, selfNode, speed, dt) {
        if (!targetPos) {
            return
        }

        let speedArr = trackTarget(targetPos.x, targetPos.y, selfNode.position.x, selfNode.position.y, speed * dt);

        selfNode.getPosition(this.tornadoTempPos);
        this.tornadoTempPos.x += speedArr[0]
        this.tornadoTempPos.y += speedArr[1]
        selfNode.setPosition(this.tornadoTempPos);

        // selfNode.angle = speedArr[2] * (180 / Math.PI);

        //如果自己已经到达敌人附近，自己销毁
        if (getDistance(selfNode.position.x,selfNode.position.y,0,0)<randomNum(0,60)) {
        //   this.IsSufferTornadoIng=false;
        }
    }

    /**
     * @description: 敌人受伤方法
     * @param {*} 什么玩家攻击类型
     * @return {*}
     */    
    hurt(skillType) {
        let isCriticalHit=false;
        let damageMun;
        switch (skillType) {
            case playerSkillTypeEnum.normalArrow:
                AudioMgr.ins.playOneShot("audio/normalArrowEnemyDamage",0.6);
                damageMun = Player.ins.arrowAttackMun;
                let randCriticalHitNum=randomNum(1,10)
                if (Player.ins.arrowCriticalHit*10>=randCriticalHitNum||Player.ins.isOpenRabid) {//暴击
                    isCriticalHit=true;

                    let goBattlePet=StartSceneGameMgr.ins.getGoBattlePet();

                    if (goBattlePet&&goBattlePet.petTp.petType==1) {
                        damageMun=damageMun*3;//暴击伤害三倍
                    }
                    else{
                        damageMun+=damageMun;//暴击伤害双倍
                    }

                }
                break;
            case playerSkillTypeEnum.fireBall:
                damageMun = Player.ins.fireBallAttackMun;
                AudioMgr.ins.playOneShot("audio/FireExplode",0.6);
                //灼烧
                if (Player.ins.fireBallIsCanFiring) {
                    this.EnemyStatus = enemyStatusEnum.firing;
                }
                break;
            case playerSkillTypeEnum.spike:
                AudioMgr.ins.playOneShot("audio/spikeEenmyDamage",0.6)
                damageMun = Player.ins.spikeAttackMun;
                break;
            case playerSkillTypeEnum.starLightBullet:
                damageMun = Player.ins.starLightBulletAttackMun;
                break;
            case playerSkillTypeEnum.spinArrow:
                AudioMgr.ins.playOneShot("audio/normalArrowEnemyDamage",0.6);
                damageMun = Player.ins.spinArrowAttackMun;
                break;
            case playerSkillTypeEnum.moonSlash:
                damageMun = Player.ins.MoonAttackMun;

                //冰冻
                if (Player.ins.moonIsCanFrozen) {
                    AudioMgr.ins.playOneShot("audio/enemyFreeze",0.6)
                    this.EnemyStatus = enemyStatusEnum.frozen;
                }
                break;
            case playerSkillTypeEnum.light:
                AudioMgr.ins.playOneShot("audio/Lightning", 0.6);

                damageMun = Player.ins.lightAttackMun;

                //烧焦
                if (Player.ins.lightIsCanscorch) {
                    this.EnemyStatus = enemyStatusEnum.scorch;
                }
                break;

        }
        damageMun = Math.floor(damageMun);
        this.CurrHp -= damageMun;
        gameMgr.ins.creatMinTip(this.node.position, `${damageMun}`, isCriticalHit);

        let goBattlePet1 = StartSceneGameMgr.ins.getGoBattlePet();
        if (goBattlePet1 && goBattlePet1.petTp.petType == 0) {
            //持有宠物蜜蜂毒刺技能
            this.schedule(() => {
                let poisoningDamageNun = Math.floor(damageMun / 5)
                this.currHp -= poisoningDamageNun;
                gameMgr.ins.creatMinTip(v3(this.node.position.x, this.node.position.y + 30, 0), `${poisoningDamageNun}`, false, "3EDF00");
                if (this.currHp <= 0) {
                    this.die();
                    return;
                }
                //扣血效果
                if (this.EnemyStatus != enemyStatusEnum.frozen && this.EnemyStatus != enemyStatusEnum.scorch) {
                    this.node.getChildByName("sp").getComponent(sp.Skeleton).color = Color.RED
                    tween(this.node)
                        .tag(12)
                        .delay(0.1)
                        .call(() => {
                            this.node.getChildByName("sp").getComponent(sp.Skeleton).color = Color.WHITE
                        })
                        .start()
                }

            }, 0.3, 1, 0.7)
        }
     

    }



    die() {
        if (this.isDie == false) {
            AudioMgr.ins.playOneShot("audio/enemyDie",0.6);
            this.isDie = true;
            Player.ins.CurrSkillEXP+=1;
            UserInfo.todayBeatEnemyNum+=1;
            this.node.getChildByName("dieDragon").active = true
            let stats=this.node.getChildByName("dieDragon").getComponent(dragonBones.ArmatureDisplay).playAnimation("Sprite",1)
            stats.currentTime=0;
            this.scheduleOnce(() => {
                if (EnemyMgr.ins.enemyNodeDic.containsValue(this.node)) {
                    EnemyMgr.ins.enemyNodeDic.deleteValue(this.node);
                }
                PoolMgr.getIns().poolPut("enemy", this.node)
                if (gameMgr.ins.IsPlayerDieTimeDowning == true) {

                    if(this.isAttacking){
                        if(gameMgr.ins.attackEnemyList.length>0){
                            if(gameMgr.ins.attackEnemyList.indexOf(this.enemyId)!== -1){
                                for (let i = gameMgr.ins.attackEnemyList.length - 1; i >= 0; i--) {
                                    if (gameMgr.ins.attackEnemyList[i] == this.enemyId) {
                                        gameMgr.ins.attackEnemyList.splice(i, 1);
                                    }
                                }
                            }
                        }
                    }
       
                    // if (gameMgr.ins.attackEnemyList.length<=0) {//取消玩家死亡倒计时
                    //     console.log("场上没有正在攻击的敌人了，取消死亡倒计时")
                    //     gameMgr.ins.IsPlayerDieTimeDowning = false
                    //     gameMgr.ins.TempUpdatePlayerDieTimeDown = 0;
                    // }
                }

            }, 0.15);

        }

    }


      
}


